package top.revery.task.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import top.revery.api.entity.user.BaseMyCollection;
import top.revery.api.entity.user.BaseUserPageWorks;
import top.revery.api.entity.user.BaseUserWorks;
import top.revery.task.dto.UserPageWorksDto;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import java.util.Map;

/**
 * @author denghao
 * @title
 * @package
 * @date 2019/12/23 10:26
 */

@Service
@Transactional
public class UserPageWorksService {
    @Autowired
    private UserPageWorksDto userPageWorksDto;

    public Page<BaseUserPageWorks> findPage(int pageNum, int pageSize, Map map) {
        Sort.Order order = new Sort.Order(Sort.Direction.DESC, "playVolume");
        Specification<BaseUserPageWorks> specification = createSpecification(map);
        PageRequest pageRequest = PageRequest.of(pageNum - 1, pageSize,Sort.by(order));
        return userPageWorksDto.findAll(specification, pageRequest);
    }

    private Specification<BaseUserPageWorks> createSpecification(Map map) {
        return new Specification<BaseUserPageWorks>() {
            @Override
            public Predicate toPredicate(Root<BaseUserPageWorks> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
                Predicate predicate = cb.conjunction();
                //id
                if (map.get("id") != null && !"".equals(map.get("id"))) {
                    predicate.getExpressions().add(cb.equal(root.get("id"), map.get("id")));
                }
                if (map.get("name") != null && !"".equals(map.get("name"))) {
                    predicate.getExpressions().add(cb.like(root.get("name"), "%"+(String) map.get("name")+"%"));
                }
                if (map.get("type") != null && !"".equals(map.get("type"))) {
                    predicate.getExpressions().add(cb.equal(root.get("type"), map.get("type")));
                }
                if (map.get("status") != null && !"".equals(map.get("status"))) {
                    predicate.getExpressions().add(cb.equal(root.get("status"), map.get("status")));
                }
                if (map.get("worksType") != null && !"".equals(map.get("worksType"))) {
                    predicate.getExpressions().add(cb.equal(root.get("worksType"), map.get("worksType")));
                }


                return predicate;
            }
        };
    }
}
